import {
	defineStore
} from 'pinia';
import userApi from '@/sheep/api/user';
import ygbPayApi from '@/ygb/api/pay.js';
import { tokenName} from "@/ygb/config/index.js"
import commissionApi from '@/sheep/api/commission';
import $share from '@/sheep/platform/share';
import {
	isEmpty,
	cloneDeep,
	clone
} from 'lodash';
import cart from './cart';
import app from './app';
import association from '@/association/store';
import {
	showAuthModal
} from '@/sheep/hooks/useModal';
import sheep from '@/sheep';
import assApi from '@/association/api'
import {udidName} from "@/sheep/config/index.js"
// #ifdef APP
import $store from '@/im/store/im';
// #endif
// 默认用户信息
const defaultUserInfo = {
	id:'',
	avatar: '', // 头像
	nickname: '', // 昵称
	gender: 0, // 性别
	mobile: '', // 手机号
	money: '--', // 余额
	refund_money: '--', // 返现余额
	commission: '--', // 佣金
	score: '--', // 积分
	verification: {}, // 认证字段
	isVip_1: 0,
	isVip_2: 0,
	isVip_3: 0,
	isVip_4: 0,
	machine_info: [],
	collect_amount: '--',
	care_amount: '--',
	fans_amount: '--'
};
// 默认订单、优惠券等其他资产信息
const defaultNumData = {
	coupons_num: '--',
	order_num: {
		aftersale: 0,
		nocomment: 0,
		noget: 0,
		nosend: 0,
		unpaid: 0,
	},
};
const user = defineStore({
	id: 'user',
	state: () => ({
		userInfo: clone(defaultUserInfo), // 用户信息
		isLogin: !!uni.getStorageSync('hotelToken'), // 登录状态
		numData: cloneDeep(defaultNumData), // 用户其他数据
		agentInfo: {}, // 分销商信息
		lastUpdateTime: 0, // 上次更新时间
		shareInfo: {
			shareId: '',//分享来源者id
			goodsId: '',//商品id
			share_log_id:'',//分享记录ID,
		},
	}),
	actions: {

		async getCountInfo() {
			let {
				error,
				data
			} = await assApi.info.getInfo()
			this.userInfo.collect_amount = data?.collect_amount || 0
			this.userInfo.care_amount = data?.care_amount || 0
			this.userInfo.fans_amount = data?.fans_amount || 0
		},
		// 获取个人信息
		async getInfo() {
			const {
				error,
				data
			} = await userApi.profile();
			if (error !== 0) return;
			this.userInfo = data;
			// #ifdef APP
			try {
				let tokenData = await ygbPayApi.getToken(data.mobile)
				if(tokenData.error == 0){
					uni.setStorageSync(tokenName,tokenData.data.Authorization[0])
				}
				console.log('tokenData',tokenData)
			} catch (error) {
				console.log('tokenData-error',error)
			}
			// #endif
			await this.userEncode(data.id)
			// #ifdef APP
			$store().imLogin(this.userInfo.mobile)
			// #endif
			return Promise.resolve(data);
		},
		//加密用户id
		async userEncode(user_id) {
			const res = await userApi.userEncode({
				encrypt: user_id
			});
			if (res.error == 0) {
				console.log('res.data:', res.data);
				uni.setStorageSync('code', res.data);
			}
		},
		getUndeadCount(mobile) {
			uni.request({
				url: 'https://liuliangbenben.rchz.top/api/settings/getTotalUnreadNum',
				data: {
					mobile: mobile,
					platform: udidName
				},
				success: (res) => {
					let dot = res.data.data.total_unread_num
					if (dot > 0) {
						sheep.$store('app').updotList({
							show: true,
							num: dot
						}, 3)
					} else {
						sheep.$store('app').updotList({
							show: false,
							num: 0
						}, 3)
					}
				}
			});
		},
		getUserSig(identifier) {
			uni.request({
				url: 'https://liuliangbenben.rchz.top/index.php/api/settings/createSign', //仅为示例，并非真实接口地址。
				data: {
					identifier: identifier
				},
				success: (res) => {
					wx.$app.login({
						userID: this.userInfo.mobile,
						userSig: res.data.data.userSig
					}).then((ress) => {}).catch((err) => {})
				}
			});
		},
		// 获取分销商信息
		async getAgentInfo() {
			const res = await commissionApi.agent();
			if (res.error === 0) {
				this.agentInfo = res.data;
			}
			return Promise.resolve(res);
		},
		// 获取订单、优惠券等其他资产信息
		async getNumData() {
			const {
				error,
				data
			} = await userApi.data();
			if (error === 0) {
				this.numData = data;
			}
		},
		// 设置token
		setToken(token = '') {
			if (token === '') {
				this.isLogin = false;
				uni.removeStorageSync('hotelToken');

			} else {
				this.isLogin = true;
				uni.setStorageSync('hotelToken', token);

				this.loginAfter();
			}
			return this.isLogin;
		},
		// 更新用户相关信息 (手动限流 5秒之内不刷新)
		async updateUserData() {
			if (!this.isLogin) {
				this.resetUserData();
				return;
			}
			const nowTime = new Date().getTime();
			if (this.lastUpdateTime + 5000 > nowTime) return;
			await this.getInfo();
			await this.getNumData();
			await this.getCountInfo()
			this.lastUpdateTime = nowTime;
			return this.userInfo;
		},
		// 重置用户默认数据
		resetUserData() {
			this.setToken();
			this.userInfo = clone(defaultUserInfo);
			this.numData = cloneDeep(defaultNumData);
			this.agentInfo = {};
			cart().emptyList();
			uni.removeStorageSync('code');
		},
		// 登录后
		async loginAfter() {
			await this.updateUserData();
			cart().getList();
			// 登录后设置全局分享参数
			$share.getShareInfo();
			// 提醒绑定手机号
			if (app().platform.bind_mobile && !this.userInfo.verification?.mobile) {
				showAuthModal('changeMobile');
			}
		},
		// 登出
		async logout(force = false) {
			if (!force) {
				const {
					error
				} = await userApi.logout();
				if (error === 0) {
					this.resetUserData();
				}
			}
			if (force) {
				this.resetUserData();
			}
			return !this.isLogin;
		},
		// 更新入住人信息
		upcheckinData(data) {
			this.checkInData = data
		},
		// 重置入住人信息
		resetcheckinData() {
			this.checkInData = {}
		},
		//商品分享
		clearShareInfo() {
			this.shareInfo = {
				shareId: '',
				goodsId: '',
				share_log_id:'',
			}
		},
		setShareInfo(shareInfo){
			this.shareInfo  = shareInfo
		},
		//商品分享
	},
	persist: {
		enabled: true,
		strategies: [{
			key: 'user-store',
			// #ifdef H5
			storage: localStorage, //存储的位置，默认为sessionStorage
			// #endif
		}, ],
	},
});
export default user;